import sqlite3
import os
import random
import re
import socket
from typing import *


def exit_with_msg(msg:str):
    print(msg)
    exit(-1)

def print_cmd():
    string = """
        参数错误！请按指定格式输入。如下：
        本程序 <sqlite> <table> <column>;<column>;<column>...  <label>,<label>;<label>,<label>;<label>,<label>... options...
        【参数】
        <sqlite>    sqlite数据库文件名
        <table>     sqlite数据表名
        <column>    数据表中列的名字,用英文分号分隔, 有几列就代表有几个任务
        <label>     后面再跟对应标签名，代表各个任务对应的标签
        【选项】
        --text=<text>   sqlite数据表中文本所在的列名,文本型, 默认为 sentence
        --state=<state> sqlite数据表中文本标记状态的列名，整数型，用来识别一条记录是否已经标记完成，默认为 status
        --worker=<n>      指定工作个数，默认为 1
        --index=<index>   指数据表的主键,默认为 id。 此列要求主键的值为整数型且值从1开始自增1，记录的主键之间是连续没有缺失的
        --port=<port>     服务器运行的端口号,默认为 8080
    """
    exit_with_msg(string)


def is_db_awailable(sqlite_db_name:str) -> bool:
    if(not os.path.exists(sqlite_db_name)):
        return False
    try:
        connect = sqlite3.connect(sqlite_db_name)
        cursor = connect.cursor()
        cursor.execute("select * from sqlite_master ")
        cursor.close()
        connect.close()
    except:
        return False
    return True


def is_tb_awailable(sqlite_db_name:str, table_name:str)->bool:
    try:
        connect = sqlite3.connect(sqlite_db_name)
        cursor = connect.cursor()
        cursor.execute("select * from %s" % (table_name))
        cursor.close()
        connect.close()
    except:
        return False
    return True

def is_col_awailable(sqlite_db_name:str, table_name:str, column_name)->bool:
    if(len(re.findall(r"^\d+$", column_name)) != 0):
        return False
    try:
        connect = sqlite3.connect(sqlite_db_name)
        cursor = connect.cursor()
        cursor.execute("select %s from %s" % (column_name, table_name))
        cursor.close()
        connect.close()
    except:
        return False
    return True

def generate_identifier(n:int, l:int) -> List[str]:
    """
    产生标识符
    :param n: 产生的个数
    :param l: 产生的长度
    :return : 返回一个标识符列表
    """
    dict = "abcdefghijklmnopqrstvuwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
    identifiers = []
    while len(identifiers) < n:
        string_buffer = ""
        for i in range(l):
            string_buffer += dict[random.randint(0, len(dict) - 1)]
        if not string_buffer in identifiers:
            identifiers.append(string_buffer)
    return identifiers

def get_row_count(sqlite_db_name:str, table_name:str):
    """
    获取某个表的记录个数
    :param sqlite_db_name: sqlite数据名字
    :param table_name: 表名字
    :return: 一个整数，代表记录的个数
    """
    connect = sqlite3.connect(sqlite_db_name)
    cursor = connect.cursor()
    cursor.execute("select count(*) from %s" % (table_name))
    row_count = next(cursor)[0]
    cursor.close()
    connect.close()
    return  row_count

def get_ranges(total:int, splits:int):
    """
    得到分割范围
    :param total: 记录总个数
    :param splits: 分割的份数
    :return: [(offset, limit)...]
    """
    count = total // splits
    results = []
    for i in range(splits):
        if i < splits - 1:
            results.append((i * count, i * count + count))
        else:
            results.append((i * count, total))
    return results

def get_current_ip() ->str:
    # 获取本机计算机名称
    hostname = socket.gethostname()
    # 获取本机ip
    ip = socket.gethostbyname(hostname)
    return ip